//
//  ViewController.m
//  PhoneNumber_20
//
//  Created by dllo on 15/11/20.
//  Copyright © 2015年 mjh. All rights reserved.
//

#import "ViewController.h"
#import "MJHaddViewController.h"
#import "Person.h"
#import "MJHCoreDate.h"


@interface ViewController ()<UITableViewDataSource, UITableViewDelegate,UISearchBarDelegate>
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)UISearchBar *searchBar;
@property (nonatomic, strong)NSMutableArray *arr;
@property (nonatomic,strong)MJHCoreDate *manager;
@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableview.backgroundColor = [UIColor whiteColor];
    self.title = @"通讯录";
    self.tableview = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:self.tableview];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPerson)];
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
   
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    [self.searchBar setSearchBarStyle:UISearchBarStyleMinimal];
    [self.searchBar setShowsCancelButton:YES];
    self.searchBar.delegate = self;
    self.tableview.tableHeaderView = self.searchBar;


    
    self.manager = [MJHCoreDate shareSingleTon];
    NSLog(@"%@",[self.manager applicationDocumentsDirectory]);
    
    
//    
//    UIButton *startButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    startButton.frame = CGRectMake(0, 0, 80, 64);
//    [startButton setTitle:@"开始定位" forState:UIControlStateNormal];
//    [startButton addTarget:self action:@selector(startAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.navigationController.navigationBar addSubview:startButton];
//    
//    UIButton *startFollow = [UIButton buttonWithType:UIButtonTypeSystem];
//    startFollow.frame = CGRectMake(200, 0, 80, 64);
//    [startFollow setTitle:@"罗盘状态" forState:UIControlStateNormal];
//    [startFollow addTarget:self action:@selector(startF) forControlEvents:UIControlEventTouchUpInside];
//    [self.navigationController.navigationBar addSubview:startFollow];
//
//    UIButton *stopButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    stopButton.frame = CGRectMake(100, 0, 80, 64);
//    [stopButton setTitle:@"结束定位" forState:UIControlStateNormal];
//    [stopButton addTarget:self action:@selector(stopAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.navigationController.navigationBar addSubview:stopButton];
//
//    UIButton *stopFollow = [UIButton buttonWithType:UIButtonTypeSystem];
//    stopFollow.frame = CGRectMake(300, 0, 80, 64);
//    [stopFollow setTitle:@"跟随" forState:UIControlStateNormal];
//    [stopFollow addTarget:self action:@selector(stopF) forControlEvents:UIControlEventTouchUpInside];
//    [self.navigationController.navigationBar addSubview:stopFollow];
//    //初始化BMKLocationService
//    _locService = [[BMKLocationService alloc]init];
//    _locService.delegate = self;

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //获取查询数据的请求,相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
    NSError *error;
    NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    NSLog(@"%ld",array.count);
    self.arr = array;
    [self.tableview reloadData];
}
#pragma mark 搜索

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", searchBar.text];
    [fetchRequest setPredicate:predicate];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    self.arr = fetchedObjects;
    [self.tableview reloadData];
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    self.arr = fetchedObjects;
    [self.tableview reloadData];
}

- (void)addPerson{
    MJHaddViewController *addVC = [[MJHaddViewController alloc]init];
    [self.navigationController pushViewController:addVC animated:YES];

    
}
#pragma mark 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"resuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
    }
    cell.textLabel.text = [self.arr[indexPath.row] name];
    cell.detailTextLabel.text = [[self.arr[indexPath.row] phone] stringValue];
    return cell;
}

#pragma mark 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MJHaddViewController *addVC = [[MJHaddViewController alloc]init];
    addVC.person = self.arr[indexPath.row];
    [self.navigationController pushViewController:addVC animated:YES];
}
#pragma mark 左划删除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", [self.arr[indexPath.row] name]];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    NSLog(@"-*/-*/*-/-/*%ld",fetchedObjects.count);
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (fetchedObjects == nil) {
            NSLog(@"无");
        }else{
            for (Person *per in fetchedObjects) {
                [self.manager.managedObjectContext deleteObject:per];
            }
            [self.manager saveContext];
            NSLog(@"-*/-*/*-/-/*%ld",fetchedObjects.count);

        }
    }
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
    NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    NSLog(@"%ld",array.count);
    self.arr = array;
    [self.tableview reloadData];

}
////开始定位
//- (void)startAction{
//    //启动LocationService
//    NSLog(@"开始定位");
//    [_locService startUserLocationService];
//    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
//    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
//    _mapView.showsUserLocation = YES;//显示定位图层
//
//}
////停止定位
//- (void)stopAction{
//    [_locService stopUserLocationService];
//    _mapView.showsUserLocation = NO;
//}
////罗盘
//- (void)startF{
//    
//    NSLog(@"进入罗盘态");
//    _mapView.showsUserLocation = NO;
//    _mapView.userTrackingMode = BMKUserTrackingModeFollowWithHeading;
//    _mapView.showsUserLocation = YES;
//  
//}
////跟随状态
//- (void)stopF{
//    NSLog(@"进入跟随态");
//    
//    _mapView.showsUserLocation = NO;
//    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
//    _mapView.showsUserLocation = YES;
//
//}
//
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
// *在地图View将要启动定位时，会调用此函数
// *@param mapView 地图View
// */
//- (void)willStartLocatingUser
//{
//    NSLog(@"start locate");
//}
//
///**
// *用户方向更新后，会调用此函数
// *@param userLocation 新的用户位置
// */
//- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
//{
//    [_mapView updateLocationData:userLocation];
//    NSLog(@"heading is %@",userLocation.heading);
//}
//
///**
// *用户位置更新后，会调用此函数
// *@param userLocation 新的用户位置
// */
//- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
//{
//    //    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
//    [_mapView updateLocationData:userLocation];
//}
//
///**
// *在地图View停止定位后，会调用此函数
// *@param mapView 地图View
// */
//- (void)didStopLocatingUser
//{
//    NSLog(@"stop locate");
//}
//
///**
// *定位失败后，会调用此函数
// *@param mapView 地图View
// *@param error 错误号，参考CLError.h中定义的错误号
// */
//- (void)didFailToLocateUserWithError:(NSError *)error
//{
//    NSLog(@"location error");
//}



@end
